<!--这是社群详情组件-->
<template>
  <div class="app-container">
    <el-form v-loading="formLoading" :model="postForm" :rules="rules" ref="postForm" label-width="220px" label-position="right">
      <p class="font-family-h font-bold margin-b40 margin-t50 title"><i class="square"></i>基本信息</p>
      <el-form-item label="社群名称：" prop="name">
        <el-input v-model="postForm.name" placeholder="请输入社群名称（不超过15个字）" style="width: 650px"></el-input>
      </el-form-item>
      <el-form-item label="社群简介：" prop="intro">
        <el-input v-model="postForm.intro" placeholder="请输入社群简介（不超过40个字）" style="width: 650px"></el-input>
      </el-form-item>
      <el-form-item label="社群管理员：" prop="manager">
        <span v-if="postForm.manager" style="padding-right: 10px;">
          <img class="headImg" :src="postForm.manager.avatar"/>
          <b>{{postForm.manager.userName}}（ID：{{postForm.manager.userId}}）</b>
        </span>
        <el-button type="primary" @click="isShowAddManager=true">{{btnText}}</el-button>
      </el-form-item>
      <el-form-item label="社群头像：" prop="avatar">
        <pan-thumb :image="postForm.avatar ? postForm.avatar:require('../../../assets/default_head.png')"></pan-thumb>
        <el-button type="primary" icon="upload" style="bottom: 15px;margin-left: 40px;" @click="imagecropperShow=true">
          更换头像
        </el-button>
        <image-cropper :width="300" :height="300" url="/common/social/imageUpload" @close='closeImageCropper'
                       @crop-upload-success="cropSuccess" langType="zh"
                       :key="imagecropperKey" v-show="imagecropperShow"></image-cropper>
      </el-form-item>
      <!-- 保存到极光 -->
      <!-- <div style="border-bottom: 2px dashed #ddd;width:100%;height:1px;margin:10px 0;"></div>
      <el-form-item>
        <el-button type="success" icon="el-icon-check" v-loading="btnLoading" @click="submitForm">保存</el-button>
      </el-form-item>
     <div style="border-bottom: 2px dashed #ddd;width:100%;height:1px;margin:10px 0;"></div> -->

      <el-form-item label="最大群成员数：" prop='maxNumber'>
        <el-input v-model="postForm.maxNumber" type='number' min="0" max="5000" placeholder="500（默认为500人，最高不超过5000人））"
                  style="width: 650px"></el-input>
      </el-form-item>
      <el-form-item label="群排序：" prop="sort">
        <el-input type="number" min="0" v-model="postForm.sort" placeholder="请输入排序号，数字大排在靠前位置（不填默认为0）"
                  style="width: 650px"></el-input>
      </el-form-item>
      <p class="font-family-h font-bold margin-t50 margin-b40 title"><i class="square"></i>加入形式</p>
      <el-form-item label="收费入群：" prop="isFree">
        <el-radio-group v-model="postForm.isFree" @change="freeSelect">
          <el-radio v-for="item in freeOptions" :key="item.key" :label="item.key" :value="item.key">{{item.value}}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="入群价格：" v-if="postForm.isFree==1" prop="price">
        <el-input min="0" type="number" v-model.number="postForm.price" placeholder="请输入价格"
                  style="width: 650px"></el-input>
      </el-form-item>
      <el-form-item label="vip折扣" v-if="postForm.isFree==1" prop="vipDiscount">
        <el-input min="0" type="number" max="100" v-model.number="postForm.vipDiscount" style="width: 100px"></el-input>
        %<span>(默认不优惠)</span>
      </el-form-item>
      <el-form-item label="svip折扣" v-if="postForm.isFree==1" prop="svipDiscount">
        <el-input min="0" type="number" max="100" v-model.number="postForm.svipDiscount"
                  style="width: 100px"></el-input>
        %<span>(默认不优惠)</span>
      </el-form-item>
      <el-form-item>
        <p v-if="isFree" style="color: red;line-height: 26px;">
          注意：会员以上级别购买才可参与折扣。票价 * 比例 = 当前价格。例如 75% 同于 7.5 折，0% 即票价免费。系统默认初始化 100%</p>
      </el-form-item>


      <p class="font-family-h font-bold margin-t50 margin-b40 title"><i class="square"></i>抽成设置<span class="point">(抽成比例总和勿大于100%，即:讲师抽成比例+一级抽成比例+二级抽成比例+三级抽成比例+代理商抽成比例+合伙人抽成比例+分公司抽成比例小于等于100%)</span>
      </p>
      <el-form-item label="是否关联收益人：">
        <el-radio-group v-model="postForm.hasTeacher" @change="isTeacherSelect">
          <el-radio v-for="item in isTeacherOptions" :key="item.key" :label="item.key" :value="item.key">{{item.value}}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="选择收益人：" v-show="isTeacher">
        <multiselect style='width:650px;' v-model="teacherInfo" :options="teacherList" :loading="isLoading"
                     track-by="userId" label="name"
                     placeholder="选择收益人" selectLabel="选择" deselectLabel="删除" @select="teacherOptionSelect"
                     @search-change="syncSearchTeachers" :internalSearch="false">
          <span slot='noResult'>无结果</span>
        </multiselect>
      </el-form-item>
      <el-form-item label="讲师抽成比例(单位%)：" v-show="isTeacher">
        <el-input min="0" type="number" max="100" v-model="postForm.lecturerRatio" placeholder="讲师抽成比例"
                  style="width: 650px"></el-input>
      </el-form-item>
      <el-form-item label="第一级别抽成(单位%)：">
        <el-table :data="stage1" border style="width: 650px">
          <el-table-column label="第一级抽成比例">
            <template slot-scope="scope">
              <el-input min="0" type="number" max="100" v-model="scope.row.distL1Ratio"
                        placeholder="第一级抽成比例"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="第二级抽成比例">
            <template slot-scope="scope">
              <el-input min="0" type="number" max="100" v-model="scope.row.distL2Ratio"
                        placeholder="请输入第二级抽成比例"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="第三级抽成比例">
            <template slot-scope="scope">
              <el-input min="0" type="number" max="100" v-model="scope.row.distL3Ratio"
                        placeholder="请输入第二级抽成比例"></el-input>
            </template>
          </el-table-column>
        </el-table>
        <!-- <el-input v-model="postForm.firstStage" placeholder="第一级抽成比例" style="width:650px"></el-input> -->
      </el-form-item>
      <el-form-item label="服务商抽成比例(单位%)：" v-if="this.agentLevel > 0">
        <el-table :data="stage2" border style="width: 650px">
          <el-table-column label="代理商抽成比例">
            <template slot-scope="scope">
              <el-input min="0" type="number" max="100" v-model="scope.row.distAgentRatio"
                        placeholder="代理商抽成比例"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="合伙人抽成比例" v-if="this.agentLevel == 3">
            <template slot-scope="scope">
              <el-input min="0" type="number" max="100" v-model="scope.row.distPartnerRatio"
                        placeholder="合伙人抽成比例"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="分公司抽成比例" v-if="this.agentLevel == 3">
            <template slot-scope="scope">
              <el-input min="0" type="number" max="100" v-model="scope.row.distBranchRatio"
                        placeholder="分公司抽成比例"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item label="是否上架：">
        <el-radio-group v-model="postForm.status">
          <el-radio v-for="item in isUpOptions" :key="item.key" :label="item.key" :value="item.key">{{item.value}}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <p class="font-family-h font-bold margin-t50 margin-b40 title"><i class="square"></i>分享设置</p>
      <!--<el-form-item label="分享公众号标题：">-->
        <!--<el-input v-model="postForm.shareTitle" placeholder="请输入公众号标题" style="width: 650px"></el-input>-->
      <!--</el-form-item>-->
      <el-form-item label="分享公众号描述：">
        <el-input :maxlength=29 v-model="postForm.shareDesc" placeholder="请输入描述,不超过29个字" style="width: 650px"></el-input>
      </el-form-item>
      <el-form-item v-if="permission == 3">
        <el-button type="primary" icon="el-icon-check" v-loading="btnLoading" @click="submitForm">保存</el-button>
        <el-button type="info" @click="close">取消</el-button>
      </el-form-item>
    </el-form>
    <addManager v-show="isShowAddManager" @saveManager="saveManager" @hideAddManager="hideAddManager"></addManager>
  </div>
</template>
<script>
  import ImageCropper from '@/components/ImageCropper'
  import PanThumb from '@/components/PanThumb'
  import addManager from './addManager.vue' // 引入添加管理员
  import { saveSocialRoom, getSocialRoomDetail, getUserByKey } from '@/api/social'
  import { getMemberSearch, initMemberList } from '@/api/member'
  import { toGetCompanyInfo } from '@/api/common'
  import Multiselect from 'vue-multiselect' // 引入 vue-multiselect 组件
  import 'vue-multiselect/dist/vue-multiselect.min.css'
  import { interaction_social } from '@/utils/permission'
  import { validateSort } from '@/utils/vm'
  let timeId
  // import { getLecturerSearch } from '@/api/lecturer'

  const postForm = {
    name: null, // 社群名
    intro: null, // 社群简介
    avatar: '', // 图片（社群头像）
    isFree: 0, // 是否收费入群
    price: null, // 入群价格
    vipDiscount: 100, // vip折扣
    svipDiscount: 100, // svip折扣
    maxNumber: null, // 最大群成员数
    sort: 0, // 群排序
    status: 1, // 是否上架
    manager: null,
    hasTeacher: -1, // 是否关联讲师
    // hasCourse: -1,
    lecturerUserId: 0, // 选择讲师
    lecturerRatio: '', // 讲师抽成比例
    distL1Ratio: 0, // 第一级抽层比例
    distL2Ratio: 0, // 第二级抽层比例
    distL3Ratio: 0, // 第三级抽层比例
    distAgentRatio: 0, // 代理商抽层比例
    distPartnerRatio: 0, // 合伙人抽层比例
    distBranchRatio: 0, // 分公司抽层比例
    shareTitle: null,
    shareDesc: null
  }
  const freeOptions = [
    { key: 0, value: '否' },
    { key: 1, value: '是' }
  ]
  const isTeacherOptions = [
    // 是否关联讲师
    { key: 1, value: '是' },
    { key: -1, value: '否' }
  ]

  const isColumnOptions = [
    // 是否关联专栏
    { key: 1, value: '是' },
    { key: -1, value: '否' }
  ]
  const isCourseOptions = [
    // 是否关联专栏
    { key: 1, value: '是' },
    { key: -1, value: '否' }
  ]
  const isActivityOptions = [
    // 是否关联专栏
    { key: 1, value: '是' },
    { key: -1, value: '否' }
  ]
  const isUpOptions = [
    // 是否上架
    { key: 1, value: '立即上架' },
    { key: -1, value: '暂不上架-显示为(下架)状态' }
  ]
  const teacherOptions = [
    // 选择讲师
    { key: 0, name: '老师一啊', headImg: '../../../../build/logo.png' },
    { key: 1, name: '老师二啊', headImg: '../../../../build/successExample1.jpg' }
  ]

  export default {
    components: {
      ImageCropper,
      PanThumb,
      addManager,
      Multiselect
    },
    props: {
      // 属性
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      const checkMaxMember = (rule, value, callback) => {
        if ((value - 5000) > 0) {
          callback('最大群成员数不能大于5000')
        } else {
          callback()
        }
      }
      return {
        rules: {
          permission: 3,
          name: [{ required: true, message: '请输入社群名称', trigger: 'blur' },
            { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }],
          intro: [{ required: true, message: '请输入社群简介', trigger: 'blur' },
            { min: 1, max: 40, message: '长度在 1 到 40 个字符', trigger: 'blur' }],
          manager: [{ required: true, message: '请添加管理员', trigger: 'blur' }],
          avatar: [{ required: true, message: '请上传头像', trigger: 'blur' }],
          sort: [{ type: 'number', validator: validateSort, trigger: 'blur' }],
          selectFree: [{ required: true, message: '请选择是否收费入群', trigger: 'change' }],
          maxNumber: [{ validator: checkMaxMember, trigger: 'blur' }]
        },
        btnLoading: false,
        isLoading: false,
        agentLevel: 0,
        socialId: null,
        btnText: '添加管理员',
        imagecropperShow: false, // 是否显示图片裁剪
        imagecropperKey: 0, // 图片裁剪key
        postForm: Object.assign({}, postForm),
        freeOptions,
        isUpOptions,
        stage1: [
          { distL1Ratio: '', distL2Ratio: '', distL3Ratio: '' } // 代理商抽成比例
        ],
        stage2: [
          { distAgentRatio: '', distPartnerRatio: '', distBranchRatio: '' } // 代理商抽成比例
        ],
        // manager: {
        //   userId: null,
        //   userName: null,
        //   avatar: null,
        //   mobile: null,
        //   jgUser: null
        // },
        isTeacherOptions, // 是否关联收益人
        teacherOptions,
        isTeacher: false, // 是否显示选择收益人
        isColumnOptions, // 是否关联专栏
        isColumn: false, // 是否显示选择专栏
        isCourseOptions, // 是否关联课程
        isCourse: false, // 是否显示选择课程
        isActivityOptions, // 是否关联活动
        isActivity: false, // 是否显示选择活动
        isFree: false,
        isShowAddManager: false,
        teacherInfo: [],
        teacherList: [],
        LecturerList: [],
        formLoading: false
      }
    },
    created() {
      this.getModelPermission()
      this.getCompanyInfo()
      this.initData()
    },
    mounted() {
      this.getLecturer()
      // this.getColumn()
      // this.teacherData = this.teacherOptions // 数据库获取的讲师数据给teacherData
    },
    watch: {
      // 监听路由名称变化 重新调用数据
      $route: function(to, from) {
        console.log(to)
        if (to.name == 'editSocial') {
          this.initData()
        }
      }
    },
    methods: {
      getModelPermission() {
        this.permission = interaction_social()
      },
      initData() {
        if (this.isEdit) {
          this.socialId = this.$route.params.socialId
          getSocialRoomDetail(this.socialId).then(res => {
            this.postForm = res.data.data
            if (res.data.data.price == 0) {
              this.postForm.isFree = 0
            } else {
              this.postForm.isFree = 1
            }
            if (this.postForm.lecturerUserId == 0) {
              this.postForm.hasTeacher = -1
              this.postForm.isTeacher = false
            } else {
              this.postForm.hasTeacher = 1
              this.isTeacher = true
              this.teacherInfo = this.postForm.teacher
            }
            // console.log(this.postForm, this.postForm.hasTeacher)
            // if (this.postForm.hasTeacher == -1) {
            //   // this.postForm.hasTeacher = -1
            //   this.postForm.isTeacher = false
            // } else {
            //   // this.postForm.hasTeacher = 1
            //   this.isTeacher = true
            //   this.teacherInfo = this.postForm.teacher
            // }
            this.stage1[0].distL1Ratio = this.postForm.distL1Ratio
            this.stage1[0].distL2Ratio = this.postForm.distL2Ratio
            this.stage1[0].distL3Ratio = this.postForm.distL3Ratio
            this.stage2[0].distAgentRatio = this.postForm.distAgentRatio
            this.stage2[0].distPartnerRatio = this.postForm.distPartnerRatio
            this.stage2[0].distBranchRatio = this.postForm.distBranchRatio
            this.btnText = '更换管理员'
          }).catch(err => {
            console.log(err)
          })
        } else {
          // console.log('11111')
        }
        initMemberList().then(res => {
          const resData = res.data.data
          this.teacherList = []
          for (let i = 0; i < resData.length; i++) {
            this.teacherList.push({
              userId: resData[i].encodeUserId,
              avatar: resData[i].avatar,
              mobile: resData[i].mobile,
              status: 2,
              name: resData[i].nickname + `（ID: ${resData[i].encodeUserId}）`,
              userName: resData[i].nickname
            })
          }
        }).catch(err => {
          console.log(err)
        })
      },
      getCompanyInfo() {
        toGetCompanyInfo(this.$route.params.columnId)
          .then(res => {
            this.agentLevel = res.data.data.agentLevels + 0
          })
          .catch(err => {
            console.log(err)
          })
      },
      getLecturer() {
      },
      close() {
        this.$store.dispatch('delVisitedViews', this.$route).then((views) => {
          const latestView = views.slice(-1)[0]
          console.log(latestView)
          if (latestView) {
            this.$router.push({ path: `/interaction/social` })
          } else {
            this.$router.push('/')
          }
        })
      },
      isTeacherSelect(val) { // 是否关联讲师
        if (val == 1) {
          this.isTeacher = true
        } else {
          this.isTeacher = false
          this.postForm.lecturerUserId = 0
          this.postForm.lecturerRatio = 0
          this.teacherInfo = []
          // console.log(this.postForm.hasTeacher)
        }
      },
      isColumnSelect(val) { // 是否关联专栏
        if (val == 1) {
          this.isColumn = true
        } else {
          this.isColumn = false
        }
      },
      isCourseSelect(val) { // 是否关联课程
        // console.log(val)
        if (val == 1) {
          this.isCourse = true
        } else {
          this.isCourse = false
        }
      },
      teacherOptionSelect(selectedOption, id) {
        this.postForm.lecturerUserId = selectedOption.userId
      },
      isActivitySelect(val) { // 是否关联活动
        if (val == 1) {
          this.isActivity = true
        } else {
          this.isActivity = false
        }
      },
      syncSearchTeachers(query) {
        clearTimeout(timeId)
        // if (query !== '') {
        this.isLoading = true
        timeId = setTimeout(() => {
          getUserByKey({ query: query }).then(res => {
            this.isLoading = false
            const resData = res.data.data
            this.teacherList = []
            for (let i = 0; i < resData.length; i++) {
              this.teacherList.push({
                userId: resData[i].userId,
                avatar: resData[i].avatar,
                mobile: resData[i].mobile,
                status: 2,
                name: resData[i].userName + `（ID: ${resData[i].userId}）`,
                userName: resData[i].userName
              })
            }
          }).catch(err => {
            this.isLoading = false
            console.log(err)
          })
        }, 200)
        // }
        // else {
        //   this.isLoading = false
        //   this.teacherList = []
        // }
        // this.teacherList = this.LecturerList
        // let name = false
        // let mobile = false
        // if (query !== '') {
        //   const patt = new RegExp(query)
        //   setTimeout(() => {
        //     // this.loading = false
        //     this.teacherList = this.LecturerList.filter(item => {
        //       name = item.userName.toLowerCase()
        //         .indexOf(query.toLowerCase()) > -1
        //       mobile = patt.test(item.mobile)
        //       console.log('mobile:', item.mobile)
        //       return name || mobile
        //     })
        //   }, 200)
        // }
      },
      freeSelect(val) {
        if (val == 1) {
          this.isFree = 1
        } else {
          this.isFree = 0
        }
      },
      submitForm() {
        this.postForm.distL1Ratio = this.stage1[0].distL1Ratio
        this.postForm.distL2Ratio = this.stage1[0].distL2Ratio
        this.postForm.distL3Ratio = this.stage1[0].distL3Ratio
        this.postForm.distAgentRatio = this.stage2[0].distAgentRatio
        this.postForm.distPartnerRatio = this.stage2[0].distPartnerRatio
        this.postForm.distBranchRatio = this.stage2[0].distBranchRatio
        if (this.postForm.distL1Ratio == 0) {
          if (this.postForm.distL2Ratio != 0 || this.postForm.distL3Ratio != 0) {
            this.$message({
              message: '第一级抽成比例为0，第二三级也只能为0',
              type: 'warning'
            })
            return
          }
        }
        if (this.postForm.distL2Ratio == 0) {
          if (this.postForm.distL3Ratio != 0) {
            this.$message({
              message: '第二级抽成比例为0，第三级也只能为0',
              type: 'warning'
            })
            return
          }
        }
        if (this.postForm.name == '' || this.postForm.name == null) {
          this.$message({
            message: '社群名称必填',
            type: 'error'
          })
          return
        }
        if (this.postForm.intro == '' || this.postForm.intro == null) {
          this.$message({
            message: '社群简介必填',
            type: 'error'
          })
          return
        }
        if (this.postForm.manager == '' || this.postForm.manager == null) {
          this.$message({
            message: '社群管理员必填',
            type: 'error'
          })
          return
        }
        if (this.postForm.avatar == '' || this.postForm.intro == null) {
          this.$message({
            message: '社群头像必填',
            type: 'error'
          })
          return
        }
        if (isNaN(this.postForm.sort) || this.postForm.sort < 0) {
          this.$message({
            message: '请输入正确的排序号，且数值不能小于0',
            type: 'error'
          })
          return
        }
        if (!this.postForm.maxNumber) {
          this.postForm.maxNumber = 500
        }
        if (this.postForm.maxNumber > 5000) {
          this.$message({
            message: '社群最大成员数不能大于5000',
            type: 'error'
          })
          return
        }
        if (this.postForm.hasTeacher == 1) {
          if (this.teacherInfo == []) {
            this.$message({
              message: '请选择收益人',
              type: 'error'
            })
            return
          }
          if (parseFloat(this.postForm.lecturerRatio) < 0) {
            this.$message({
              message: '讲师抽成比例不能小于0',
              type: 'error'
            })
            return
          }
        }
        if (this.postForm.hasTeacher == 1) {
          if (parseFloat(this.postForm.lecturerRatio) + parseFloat(this.postForm.distPartnerRatio) + parseFloat(this.postForm.distBranchRatio) + parseFloat(this.postForm.firstRate) + parseFloat(this.postForm.secondRate) + parseFloat(this.postForm.thirdRate) + parseFloat(this.postForm.distAgentRatio) > 100) {
            this.$message({
              message: '讲师、一二三跟代理商、合伙人、分公司抽成比例总和不能大于100',
              type: 'error'
            })
            return
          }
        } else {
          if (parseFloat(this.postForm.distBranchRatio) + parseFloat(this.postForm.distPartnerRatio) + parseFloat(this.postForm.firstRate) + parseFloat(this.postForm.secondRate) + parseFloat(this.postForm.thirdRate) + parseFloat(this.postForm.distAgentRatio) > 100) {
            this.$message({
              message: '一二三跟代理商、合伙人、分公司抽成比例总和不能大于100',
              type: 'error'
            })
            return
          }
        }
        this.$refs.postForm.validate((valid) => {
          if (valid) {
            if (this.btnLoading) {
              return
            }
            this.btnLoading = true
            this.formLoading = true
            saveSocialRoom(this.postForm).then(res => {
              console.log(res.data)
              this.$message({
                message: res.data.data.message,
                type: 'success'
              })
              this.close()
              this.btnLoading = false
              this.formLoading = false
            }).catch(err => {
              this.btnLoading = false
              this.formLoading = false
            })
          }
        })
      },
      saveManager(manager) {
        this.postForm.manager = manager
        this.btnText = '更换管理员'
      },
      hideAddManager(msg) {
        this.isShowAddManager = false
      },
      cropSuccess(resData) {
        this.imagecropperShow = false
        this.imagecropperKey = this.imagecropperKey + 1
        this.postForm.avatar = resData.data.imageUrl
      },
      closeImageCropper() {
        this.imagecropperShow = false
      }
    }
  }
</script>
<style scoped>
  .headImg {
    width: 30px;
    height: 30px;
    vertical-align: middle;
    border-radius: 100%;
  }
</style>
